<template>
    <div class="main">
        <a-form id="formLogin" class="user-layout-login" ref="formLogin" :form="form" @submit="handleSubmit">
            <a-tabs :activeKey="customActiveKey" :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }" @change="handleTabClick">
                <!-- <a-tab-pane key="tab1" tab="账号密码登录">
                    <div style="padding-top: 4px;"></div>
                    <a-alert v-if="isLoginError && customActiveKey === 'tab1'" type="error" showIcon style="margin-bottom: 24px;" message="账户或密码错误" />
                    <a-form-item>
                        <a-input size="large" type="text" placeholder="请输入帐户名" v-decorator="['username',{rules: [{ required: true, message: '请输入帐户名' }], validateTrigger: 'change'}]">
                            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
                        </a-input>
                    </a-form-item>
                    <div style="padding-top: 4px;"></div>
                    <a-form-item>
                        <a-input size="large" type="password" autocomplete="false" placeholder="请输入密码" v-decorator="['password',{rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}]">
                            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
                        </a-input>
                    </a-form-item>
                    <div style="padding-top: 14px;"></div>
                </a-tab-pane> -->
                <a-tab-pane key="tab2" tab="手机号登录">
                    <div style="padding-top: 4px;"></div>
                    <a-alert v-if="isLoginError && customActiveKey === 'tab2'" type="error" showIcon style="margin-bottom: 24px;" message="手机号或验证码错误" />
                    <a-form-item>
                        <a-input size="large" type="text" placeholder="手机号" v-decorator="['mobile', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号' }], validateTrigger: 'change'}]">
                            <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }" />
                        </a-input>
                    </a-form-item>
                    <div style="padding-top: 4px;"></div>
                    <a-row :gutter="16">
                        <a-col class="gutter-row" :span="16">
                            <a-form-item>
                                <a-input size="large" type="text" placeholder="验证码" v-decorator="['captcha', {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]">
                                    <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
                                </a-input>
                            </a-form-item>
                        </a-col>
                        <a-col class="gutter-row" :span="8">
                            <a-button class="getCaptcha" tabindex="-1" :disabled="state.smsSendBtn" @click.stop.prevent="getCaptcha" v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"></a-button>
                        </a-col>
                    </a-row>
                    <div style="padding-top: 14px;"></div>
                </a-tab-pane>
            </a-tabs>
            <a-form-item>
                <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="state.loginBtn" :disabled="state.loginBtn">确定
                </a-button>
            </a-form-item>
        </a-form>
    </div>
</template>
<script>
    import Vue from 'vue';
    import env from '@/config/env';
    // import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha';
    import { userLogin, GetSendsms, LoginByMobile } from '@/api/passport';
    import { ACCESS_TOKEN, USER_RULE } from '@/store/mutation-types';
    import { showErrors, showError, showSuccess } from '@/utils/showMsg';
    import { mapActions } from 'vuex';
    export default {
        components: {
            // TwoStepCaptcha,
        },
        data() {
            return {
                customActiveKey: 'tab2',
                loginBtn: false,
                // login type: 0 email, 1 username, 2 telephone
                loginType: 0,
                isLoginError: false,
                requiredTwoStepCaptcha: false,
                stepCaptchaVisible: false,
                form: this.$form.createForm(this),
                state: {
                    time: 60,
                    loginBtn: false,
                    // login type: 0 email, 1 username, 2 telephone
                    loginType: 0,
                    smsSendBtn: false,
                },
                wrapperCol: { span: 24 },
            };
        },
        methods: {
            ...mapActions({
                storeLogin: 'user/Login',
                // InfoData: 'user/UserInfo',
            }),
            // 切换账号登陆还是手机号码登陆
            handleTabClick(key) {
                this.customActiveKey = key;
                this.form.resetFields()
            },
            // 登陆 //账号登陆,手机验证码登陆
            handleSubmit(e) {
                const that = this;
                e.preventDefault();
                const {
                    form: { validateFields },
                    state,
                    customActiveKey,
                    Login,
                } = this;
                state.loginBtn = true;
                const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha'];
                validateFields(validateFieldsKey, { force: true }, (err, values) => {
                    if (!err) {
                        const loginParams = {
                            // username: values.username,
                            //   password: values.password,
                        };
                        if (customActiveKey === 'tab1') {
                            loginParams['username'] = values.username
                            loginParams['password'] = values.password
                            userLogin(loginParams).then((res) => {
                                // console.log(res);
                                if (res.data.code == 1) {
                                    // console.log(res);
                                    this.isLoginError = false
                                    this.storeLogin({
                                        accessToken: res.data.data.user.token.access_token,
                                        UserData: {
                                            name: res.data.data.nickname,
                                            headimg: res.data.data.headimg ? res.data.data.headimg : require('../../assets/images/avatar.png'),
                                            UserId: res.data.data.user.id,
                                            // MarketId: res.data.data.user.m_id,
                                            // MarketName: res.data.data.user.market_name,
                                            pid: res.data.data.user.pid,
                                            identityId: res.data.data.user.identity_id,
                                            identityType: res.data.data.user.identity_type
                                        },
                                    });
                                    showSuccess(res.data.msg);
                                    this.$router.push({ path: '/' });
                                    // 延迟 1 秒显示欢迎信息
                                    setTimeout(() => {
                                        this.$notification.success({
                                            message: '欢迎',
                                            description: `${res.data.data.nickname}，欢迎回来`
                                        })
                                    }, 1000)
                                    // userMessage()
                                    //     .then(info => {
                                    //         if (info.data.code == 1) {
                                    //             // console.log(res.data);
                                    //             let data = info.data.data
                                    //             let infodata = {
                                    //                 RouterList: data.data,
                                    //                 RouteArr: data.route
                                    //             }
                                    //             Vue.ls.set(USER_RULE, infodata, env.tokenExpires);
                                    //             showSuccess(res.data.msg);
                                    //             this.$router.push({ path: '/' });
                                    //             // 延迟 1 秒显示欢迎信息
                                    //             setTimeout(() => {
                                    //                 this.$notification.success({
                                    //                     message: '欢迎',
                                    //                     description: `${res.data.data.nickname}，欢迎回来`
                                    //                 })
                                    //             }, 1000)
                                    //         } else {
                                    //             showError(info.data.msg);
                                    //         }
                                    //     });
                                    // this.InfoData()
                                } else {
                                    showError(res.data.msg);
                                    this.isLoginError = true
                                }
                                state.loginBtn = false;
                            }).catch((err) => {
                                showError(err);
                                this.isLoginError = false
                            })
                        } else {
                            loginParams['mobile'] = values.mobile
                            loginParams['code'] = values.captcha
                            LoginByMobile(loginParams).then((res) => {
                                console.log(res);
                                if (res.data.code == 1) {
                                    if(res.data.data.partner_type != 'yxn_supplier'){
                                        showError('登录账号不是商品供应商身份！');
                                        return
                                    }
                                    that.isLoginError = false
                                    that.storeLogin({
                                        accessToken: res.data.data.token.access_token,
                                        UserData: {
                                            name: res.data.data.store_name,
                                            headimg: res.data.data.store_logo ? res.data.data.store_logo : require('../../assets/images/avatar.png'),
                                            UserId: res.data.data.user_id,
                                            // MarketId: res.data.data.user.m_id,
                                            // MarketName: res.data.data.user.market_name,
                                            pid: res.data.data.p_identity_id,
                                            identityId: res.data.data.identity_id,
                                            identityType: res.data.data.identity_type
                                        },
                                    });
                                    showSuccess(res.data.msg);
                                    that.$router.push({ path: '/' });
                                    // 延迟 1 秒显示欢迎信息
                                    setTimeout(() => {
                                        that.$notification.success({
                                            message: '欢迎',
                                            description: `${res.data.data.store_name}，欢迎回来`
                                        })
                                    }, 1000)
                                } else {
                                    showError(res.data.msg);
                                    this.isLoginError = true
                                }
                                state.loginBtn = false;
                            }).catch((err) => {
                                showError(err);
                                this.isLoginError = false
                            })
                        }
                    } else {
                        setTimeout(() => {
                            state.loginBtn = false;
                        }, 600);
                    }
                })
            },
            // 获取验证码
            getCaptcha(e) {
                e.preventDefault();
                const { form: { validateFields }, state } = this;
                validateFields(['mobile'], { force: true }, (err, values) => {
                    if (!err) {
                        state.smsSendBtn = true;
                        const interval = window.setInterval(() => {
                            if (state.time-- <= 0) {
                                state.time = 60;
                                state.smsSendBtn = false;
                                window.clearInterval(interval);
                            }
                        }, 1000);
                        const hide = this.$message.loading('验证码发送中..', 0);
                        GetSendsms({ mobile: values.mobile }).then((res) => {
                            setTimeout(hide, 2500);
                            this.$notification.success({
                                message: '提示',
                                description: `验证码获取成功`,
                                duration: 8,
                            });
                        }).catch((err) => {
                            setTimeout(hide, 1);
                            clearInterval(interval);
                            state.time = 60;
                            state.smsSendBtn = false;
                            this.requestFailed(err);
                        });
                    }
                });
            },
        },
    };
</script>
<style lang="less" scoped>
    .user-layout-login {
        label {
            font-size: 14px;
        }

        .getCaptcha {
            display: block;
            width: 100%;
            height: 40px;
        }

        .forge-password {
            font-size: 14px;
        }

        button.login-button {
            padding: 0 15px;
            font-size: 16px;
            height: 40px;
            width: 100%;
        }

        .user-login-other {
            text-align: left;
            margin-top: 24px;
            line-height: 22px;

            .item-icon {
                font-size: 24px;
                color: rgba(0, 0, 0, 0.2);
                margin-left: 16px;
                vertical-align: middle;
                cursor: pointer;
                transition: color 0.3s;

                &:hover {
                    color: #1890ff;
                }
            }

            .register {
                float: right;
            }
        }
    }
</style>